package com.tools.tools;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String doPost(String url, String body){

        try{

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            if(StringUtils.isNotBlank(body)){
                HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
                httppost.setEntity(entity);
            }

            HttpResponse response = httpclient.execute(httppost);
            String result = EntityUtils.toString(response.getEntity());
            return result;

        }catch (Exception e){

            logger.error(String.format("post url %s error params %s",url,body),e);
            return "";
        }
    }

    public static String doGet(String url, List<NameValuePair> parameters){

        try{

            CloseableHttpClient httpclient = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(url);

            if(parameters != null){

                String param = EntityUtils.toString(new UrlEncodedFormEntity(parameters));
                httpGet.setURI(new URIBuilder(httpGet.getURI().toString() + "?" + param).build());
            }


            HttpResponse response = httpclient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            return result;

        }catch (Exception e){

            logger.error(String.format("get url %s error",url),e);
            return "";
        }
    }


}
